<template>
  <view class="content">
    <view class="content-top">
      <up-search
        placeholder="商品名称"
        v-model="keyword"
        @search="searchfun"
        :showAction="false"
      ></up-search>
      <view class="search" @click="screen">
        <image src="@/static/cloudlibrary/search.png" mode="scaleToFill" />
      </view>
    </view>

    <view class="top-btn">
      <view class="date-select">
        <picker
          mode="date"
          :value="date"
          :start="startDate"
          fields="month"
          :end="endDate"
          @change="bindDateChange"
        >
          <view class="content-time"
            ><text>{{ DateSwitching(date, "-", 2) }}</text
            ><image src="@/pages/team/static/ls-dowe.png" mode="scaleToFill"
          /></view>
        </picker>
        <!-- <u-datetime-picker
          hasInput
          :show="show"
          v-model="dateValue"
          mode="year-month"
          @confirm="confirmDate"
        >
          <image
            src="@/static/cloudlibrary/search.png"
            mode="scaleToFill"
        /></u-datetime-picker> -->
      </view>

      <view class="btn-right">
        <view class="top-item-select">
          <up-tabs
            :activeStyle="{
              color: '#01ADA8',
              fontSize: '28rpx',
              backgroundColor: '#ffffff',
              padding: '10rpx 24rpx',
              borderRadius: '40rpx',
              border: '2rpx solid #01ADA8',
            }"
            :inactiveStyle="{
              color: '#000000',
              fontSize: '28rpx',
              backgroundColor: '#FFFFFF',
              padding: '10rpx 24rpx',
              borderRadius: '400rpx 400rpx 400rpx 400rpx',
            }"
            lineColor="#ffffff"
            itemStyle="padding-left: 16rpx; padding-right: 0rpx; height: 34px;"
            :list="listTabs"
            @click="selectType"
            :current="current"
          ></up-tabs>
        </view>
      </view>
    </view>

    <view class="top-card">
      <view class="top-card-title"
        >本月{{
          typeIndex == 1 ? "入库" : typeIndex == -1 ? "出库" : ""
        }}统计(件)</view
      >
      <view class="top-card-text">{{
        typeIndex == 1
          ? Math.abs(recordTotalData.add) || 0
          : typeIndex == -1
          ? Math.abs(recordTotalData.sub) || 0
          : recordTotalData.total || 0
      }}</view>
    </view>

    <view v-show="recordData && recordData.length > 0">
      <view
        class="list"
        :class="item.class == 201 ? 'list201' : ''"
        v-for="(item, index) in recordData"
        :key="index"
        @click.stop="goDetails(item.id)"
      >
        <view class="list-top" @click.stop>
          <view class="list-top-title">
            单据编号：{{ item.id }}
            <up-copy :content="item.id"
              ><image src="@/static/cloudlibrary/copy-img.png" mode="widthFix"
            /></up-copy>
          </view>
          <view class="list-top-right">{{ item.class_text }}</view>
        </view>
        <u-line length="85%" class="notuse-line"></u-line>

        <view class="list-footer">
          <view class="list-footer-left">
            <view class="footer-img">
              <image :src="item.product.image" mode="scaleToFill"
            /></view>
            <view class="footer-title">
              <view class="title-top"
                >商品名称：{{ item.product.store_name }}</view
              >
              <view class="title-middle">{{ item.create_time }}</view>
              <view v-if="item.class == 102"
                >提货人:{{
                  item.order && item.order.buyer && item.order.buyer.name
                    ? item.order.buyer.name
                    : item.order &&
                      item.order.buyer &&
                      item.order.buyer.nickname
                    ? item.order.buyer.nickname
                    : "-"
                }}</view
              >
              <view v-if="item.class == 201"
                >物流：{{ item.express_name || "-" }}
                {{ item.express_num <= 0 ? "-" : item.express_num }}
              </view>
            </view>
          </view>

          <view class="list-footer-right">
            <!-- <view class="list-footer-right-left" v-if="item.price > 0"
              >￥{{ formatPrice(item.price) }}</view
            >
            <view v-if="item.type > 0" class="list-footer-right-right"
              >+{{ item.quantity }}</view
            > -->
            <view class="list-footer-right-right">{{ item.value }}</view>
            <view
              v-if="item.class == 201"
              class="express-content"
              @click.stop="seeaddress(item)"
              >查看物流</view
            >
          </view>
        </view>
      </view>
    </view>
    <view class="nodate-bt" v-if="recordData.length === 0">
      <image src="/static/nodate/datas.png" mode="widthFix"></image>
    </view>
    <uni-load-more color="#c6c5c3" :status="status" />

    <!-- 筛选 -->
    <u-popup
      :show="showPopup"
      mode="bottom"
      round="10"
      @close="close"
      @open="open"
      closeable
    >
      <view class="popup-content">
        <view class="popup-content-title">筛选</view>
        <u-line></u-line>
        <view class="popup-content-dec">
          <view class="popup-content-card">
            <text>类型</text>
            <view class="popup-content-card-btn">
              <view
                class="popup-button"
                v-for="(item, index) in listTabs1"
                :key="index"
                @click="selectListType(item.value)"
                :class="typeIndex === item.value ? 'popup-button-active' : ''"
                >{{ item.name }}</view
              >
            </view>
          </view>
          <!-- <view class="popup-content-card">
            <text>子分类</text>
            <view class="popup-content-card-btn">
              <view
                class="popup-button popup-button-active"
                v-if="addselect == 0"
                >全部</view
              >
              <view v-for="(item, index) in classData" :key="index">
                <button
                  class="popup-button"
                  v-if="
                    addselect == 0 ||
                    (addselect == 1 && index < 200) ||
                    (addselect == -1 && index >= 200)
                  "
                  @click="selectClassType(index)"
                  :class="
                    type_classIndex === index ? 'popup-button-active' : ''
                  "
                  :disabled="isDisadbled"
                >
                  {{ item }}
                </button>
              </view>
              
            </view>
          </view> -->
        </view>

        <view class="popup-content-box">
          <view class="popup-content-bt">
            <view class="popup-content-qx" @click="closepopup">取消</view>
            <view class="popup-content-cl" @click="popupSubmit">筛选</view>
          </view>
        </view>
      </view>
    </u-popup>

    <up-popup
      v-model:show="addresslistshow"
      round="20"
      @close="close"
      :closeable="true"
      :closeOnClickOverlay="true"
    >
      <view class="addresscontent">
        <view class="addresscontent-content" v-if="addresslist.length <= 0">
          查询不到物流信息
        </view>
        <view class="addresscontent-two">
          <up-steps current="0" direction="column">
            <up-steps-item
              v-for="(item, index) in addresslist"
              :key="index"
              :title="item.context"
              :desc="item.time"
            >
            </up-steps-item>
          </up-steps>
        </view>
      </view>
    </up-popup>
  </view>
</template>

<script setup>
import { inject, ref } from "vue";
import { onLoad, onShow, onReachBottom } from "@dcloudio/uni-app";
import { shopRecord, classApi, recordTotalApi } from "@/services/cloudlibrary";
import dayjs from "dayjs";
import { formatPrice } from "@/utils/formatPrice";
import { orderexpress } from "@/services/order";

onShow(() => {
  getList(1);
  getClass();
  recordTotal();
});
onLoad((e) => {
  form.value.shop_id = e.shop_id ? e.shop_id : "";
});

// 创建响应式数据
const current = ref(0);
const showPopup = ref(false);
const type = ref("");
const type_class = ref("");
const keyword = ref("");
const show = ref(false);
const dateValue = ref(Date.now());
const listTabs = ref([
  { name: "全部", value: "" },
  { name: "入库", value: 1 },
  { name: "出库", value: -1 },
]);

const listTabs1 = ref([
  { name: "全部", value: 0 },
  { name: "入库", value: 1 },
  { name: "出库", value: -1 },
]);

const classData = ref({});

const getClass = async () => {
  try {
    // 发送请求
    let res = await classApi();
    if (res.code === 200) {
      classData.value = res.data;
    }
  } catch (e) {
    uni.showToast({
      title: e.info,
      icon: "none",
    });
  }
};

// 我的库存商品
const recordData = ref([]);
const status = ref("more");
const form = ref({
  page: 1,
  limit: 20,
  month: getDate(),
  shop_id: "",
});
const recordTotalData = ref({});
const recordTotalFrom = ref({});
const typeIndex = ref(0);
const type_classIndex = ref(0);
const addselect = ref(0);
const isDisadbled = ref(false);

const date = ref(null);
// 日期选择器
const currentDate = getDate({
  format: true,
});

date.value = getDate({
  format: true,
});

const startDate = ref(null);
const endDate = ref(null);

startDate.value = getDate("start");
endDate.value = getDate({
  format: true,
});

function getDate(type) {
  const date = new Date();
  let year = date.getFullYear();
  let month = date.getMonth() + 1;
  // let day = date.getDate();

  if (type === "start") {
    year = year - 60;
  } else if (type === "end") {
    year = year;
  }
  month = month > 9 ? month : "0" + month;
  // day = day > 9 ? day : '0' + day;
  return `${year}-${month}`;
}
const DateSwitching = (Data, formString, type) => {
  let newdate = "";
  if (type == 1) {
    newdate = Data.split(formString);

    return newdate[0] + "年";
  }
  if (type == 2) {
    newdate = Data.split(formString);

    return newdate[0] + "年" + newdate[1] + "月";
  }
  if (type == 3) {
    newdate = Data.split(formString);

    return newdate[0] + "年" + newdate[1] + "月" + newdate[2] + "日";
  }
};

function bindDateChange(e) {
  recordData.value = [];
  form.value.page = 1;
  date.value = e.detail.value;
  form.value.month = e.detail.value;
  recordTotal();
  getList(1);

  //   getChangeList(date.value);
}

// 库存记录统计
const recordTotal = async () => {
  recordTotalFrom.value = {
    ...form.value,
    type: typeIndex.value == 0 ? "" : typeIndex.value,
    type_class: type_classIndex.value == 0 ? "" : type_classIndex.value,
    keyword: keyword.value,
    shop_id: form.value.shop_id,

    // month: dayjs(dateValue.value).format(`YYYY-MM`),
  };
  try {
    // 发送请求
    let res = await recordTotalApi(recordTotalFrom.value);
    if (res.code === 200) {
      recordTotalData.value = res.data;
    }
  } catch (e) {
    uni.showToast({
      title: e.info,
      icon: "none",
    });
  }
};

const goDetails = (id) => {
  uni.navigateTo({
    url:
      "/pages/cloudlibrary/inventoryRecords/details?id=" +
      id +
      "&shop_id=" +
      form.value.shop_id,
  });
};
//下拉触底
onReachBottom(() => {
  // 触发下拉触底时执行的操作
  if (form.value.page <= pages.value) {
    getList();
  }
});

const pages = ref(0);

const getList = async (type) => {
  if (type == 1) {
    recordData.value = [];
    form.value.page = 1;
  }

  let dates = {
    ...form.value,
    type: typeIndex.value == 0 ? "" : typeIndex.value,
    type_class: type_classIndex.value == 0 ? "" : type_classIndex.value,
    keyword: keyword.value,
    // month: dayjs(dateValue.value).format(`YYYY-MM`),
  };
  try {
    status.value = "loading";
    // 发送请求
    let res = await shopRecord(dates);

    if (res.code === 200) {
      res.data.list.forEach((item, index) => {
        res.data["recordTotal"] = 0;
        res.data.recordTotal += item.quantity;
      });
      let arr = [];
      arr = res.data.list;
      recordData.value = recordData.value.concat(arr);
      total.value = res.data.page.total;
      pages.value = res.data.page.pages;

      if (res.data.list.length < form.value.limit) {
        status.value = "no-more";
      } else {
        status.value = "more";
      }
      form.value.page++;
    }
  } catch (e) {
    status.value = "no-more";
  }
};

const selectType = (item, index) => {
  type_classIndex.value = 0;
  recordData.value = [];
  form.value.page = 1;
  typeIndex.value = item.value;
  recordTotal();
  getList(1);
};

const selectListType = (index) => {
  if (index == 0) {
    typeIndex.value = 0;
  } else {
    typeIndex.value = index;
  }

  if (index === 1) {
    addselect.value = 1;
    isDisadbled.value = false;
  } else if (index == -1) {
    addselect.value = -1;
    isDisadbled.value = false;
  } else {
    addselect.value = 0;
    type_classIndex.value = "";
    isDisadbled.value = true;
  }
};
const selectClassType = (index) => {
  recordData.value = [];
  form.value.page = 1;
  type_classIndex.value = index;
  recordTotal();
  getList();
};

// 搜索
const searchfun = () => {
  recordData.value = [];
  form.value.page = 1;
  form.value.keyword = keyword.value;
  recordTotal();
  getList(1);
};

const confirmDate = () => {
  recordData.value = [];
  form.value.page = 1;
  recordTotal();
  getList();
};

const close = () => {
  addresslistshow.value = false;
  showPopup.value = false;
};

const screen = () => {
  showPopup.value = true;
  if (typeIndex.value === 1) {
    current.value = 1;
    addselect.value = 1;
    isDisadbled.value = false;
  } else if (typeIndex.value === -1) {
    current.value = 2;
    addselect.value = -1;
    isDisadbled.value = false;
  } else {
    current.value = 0;
    addselect.value = 0;
    isDisadbled.value = true;
    typeIndex.value = 0;
  }
};

const closepopup = () => {
  addselect.value = 0;
  current.value = 0;
  typeIndex.value = 0;
  type_classIndex.value = "";
  showPopup.value = false;
  recordData.value = [];
  form.value.page = 1;
  recordTotal();
  getList(1);
};

// 筛选确认
const popupSubmit = () => {
  if (typeIndex.value === 1) {
    current.value = 1;
  } else if (typeIndex.value === -1) {
    current.value = 2;
  } else {
    current.value = 0;
    typeIndex.value === 0;
  }
  showPopup.value = false;
  recordData.value = [];
  form.value.page = 1;
  recordTotal();
  getList(1);
};

const delivery_name = ref("");
const delivery_id = ref("");
const addresslistshow = ref(false);
const addresslist = ref([]);
const getorderexpress = async () => {
  try {
    let resaddress = await orderexpress({
      delivery_name: delivery_name.value,
      delivery_id: delivery_id.value,
    });
    addresslistshow.value = true;
    addresslist.value = resaddress.data.data;
  } catch (e) {}
};

const seeaddress = (item) => {
  delivery_name.value = item.express_name;

  delivery_id.value = item.express_num;
  getorderexpress();
  addresslistshow.value = true;
};
</script>

<style lang="scss" scoped>
@import "./index.scss";
</style>
